package com.ktg.mes.pro.controller;

import java.math.BigDecimal;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.google.gson.internal.LinkedTreeMap;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.core.domain.model.SqlResult;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.chanjet.content.DeliveryOrderContent;
import com.ktg.mes.chanjet.content.GetVoucherContent;
import com.ktg.mes.chanjet.entity.TpItem;
import com.ktg.mes.chanjet.response.GetVoucherResponse;
import com.ktg.mes.chanjet.service.TpItemService;
import com.ktg.mes.chanjet.spi.ChanjetSpi;
import com.ktg.mes.chanjet.vo.QueryOrderVo;
import com.ktg.mes.md.domain.*;
import com.ktg.mes.md.service.*;
import com.ktg.mes.pro.domain.ProTask;
import com.ktg.mes.pro.domain.ProWorkorder;
import com.ktg.mes.pro.service.IProTaskService;
import com.ktg.mes.pro.service.IProWorkorderService;
import com.ktg.mes.util.LGLeftJoinQueryWrapper;
import com.ktg.mes.util.StaticValue;
import com.ktg.mes.wm.domain.*;
import com.ktg.mes.wm.service.*;
import org.apache.commons.collections.map.LinkedMap;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.pro.domain.ProItemNeed;
import com.ktg.mes.pro.service.IProItemNeedService;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 客戶产品需求Controller
 *
 * @author byteco
 * @date 2022-12-12
 */
@RestController
@RequestMapping("/pro/proItemNeed")
public class ProItemNeedController extends BaseController
{
    @Autowired
    private IProItemNeedService proItemNeedService;

    @Autowired
    private IMdItemService mdItemService;

    @Autowired
    private TpItemService tpItemService;
    @Autowired
    private IMdProductStatisticsBomService statisticsBomService;
    @Autowired
    private IWmStockWillOutService wmStockWillOutService;

    @Autowired
    private IMesScalesOrderItemService mesScalesOrderItemService;


    @Autowired
    private IMesScalesOrderService iMesScalesOrderService;
    @Autowired
    private IWmStockOutService wmStockOutService;


    @Autowired
    private IWmIssueLineService issueLineService;


    @Autowired
    private ChanjetSpi chanjetSpi;


    @Autowired
    private IWmItemRecptLineService iWmItemRecptLineService;


    /**
     * 查询客戶产品需求列表
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:list')")
    @GetMapping("/list")
    public Result<IPage<ProItemNeed>> list(ProItemNeed proItemNeed,
                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                            HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询客戶产品需求列表",req,null);
        try {
//            Page<ProItemNeed> page = new Page<ProItemNeed>(pageNo, pageSize);
//            IPage<ProItemNeed> pageList = proItemNeedService.queryPageList(proItemNeed,page);
            Map map = req.getParameterMap();

            LGLeftJoinQueryWrapper lgLeftJoinQueryWrapper = new LGLeftJoinQueryWrapper<>(proItemNeed,map,pageNo,pageSize);
            lgLeftJoinQueryWrapper.setDefaultDateFormat("yyyy-MM-dd HH:mm:ss");
            if(map != null && map.get("type") != null){
                Integer a = Integer.valueOf(((String[]) map.get("type"))[0]);
                if(a == 1){
                    lgLeftJoinQueryWrapper.whereOtherSql("and need_date >= current_date and shipped_type =  0");
                    lgLeftJoinQueryWrapper.orderBy("need_date");
                }else if(a == 2){
                    lgLeftJoinQueryWrapper.whereOtherSql("and shipped_type in (10,20)");
                    lgLeftJoinQueryWrapper.setSelectColumn("*,(SELECT sum(quantity) AS quantity FROM  wm_stock_out WHERE wm_stock_out.item_need_id = A.\"recordId\"::varchar) as outquantity");
                }else if(a == 3){
                    lgLeftJoinQueryWrapper.whereOtherSql("and shipped_type =  30");
                }else if (a == 5){
                    lgLeftJoinQueryWrapper.whereOtherSql("and need_date < current_date and shipped_type =  0");
                    lgLeftJoinQueryWrapper.orderByDesc("need_date");
                }
            }

            IPage<JSONObject> pageList = wmStockOutService.lgPageMapList(lgLeftJoinQueryWrapper);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 查询需要组装入库的客戶产品需求列表
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:list')")
    @GetMapping("/needAssemble")
    public Result<IPage<ProItemNeed>> needAssemble(ProItemNeed proItemNeed,
                                           @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                           HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询客戶产品需求列表",req,null);
        try {
//            Page<ProItemNeed> page = new Page<ProItemNeed>(pageNo, pageSize);
//            IPage<ProItemNeed> pageList = proItemNeedService.queryPageList(proItemNeed,page);
            Map map = req.getParameterMap();

            LGLeftJoinQueryWrapper lgLeftJoinQueryWrapper = new LGLeftJoinQueryWrapper<>(proItemNeed,map,pageNo,pageSize);
            lgLeftJoinQueryWrapper.setDefaultDateFormat("yyyy-MM-dd HH:mm:ss");
            lgLeftJoinQueryWrapper.whereOtherSql("and need_date >= current_date and shipped_type != 30");
            lgLeftJoinQueryWrapper.orderBy("need_date");
            String sql = "COALESCE((SELECT sum(quantity) FROM wm_stock_will_out  WHERE stock_type = 'wm_material_stock'  AND stock_id LIKE \"itemCode\"::VARCHAR||':%'  AND link_type = 'pro_item_need'  AND link_id = record_id::varchar),0)";
            lgLeftJoinQueryWrapper.setSelectColumn("*,"+sql+" as willout");
            IPage<JSONObject> pageList = wmStockOutService.lgPageMapList(lgLeftJoinQueryWrapper);

            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }



    /**
     * 生产排产,获取生产排产预出的客户产品需求
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:list')")
    @Log(title = "生产排产,获取生产排产预出的客户产品需求", businessType = BusinessType.EXPORT)
    @GetMapping("/needAssembleFromProWorkorder")
    public Result<IPage<ProItemNeed>> needAssembleFromProWorkorder(@RequestParam(name="workorderId") String workorderId,
                                                   HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询客戶产品需求列表",req,null);
        try {
//            Page<ProItemNeed> page = new Page<ProItemNeed>(pageNo, pageSize);
//            IPage<ProItemNeed> pageList = proItemNeedService.queryPageList(proItemNeed,page);
            if (StringUtils.isEmpty(workorderId)){
                return apiLog.fail("生产工单ID不能为空");
            }
            WmStockWillOut willOut = new WmStockWillOut();
            willOut.stockTableClass(ProWorkorder.class,Long.valueOf(workorderId));
            willOut.setLinkType("pro_item_need");
            QueryWrapper<WmStockWillOut> wmStockWillOutQueryWrapper = new QueryWrapper<>(willOut);
            List<WmStockWillOut> wmStockOutList = wmStockWillOutService.list(wmStockWillOutQueryWrapper);

            String needIds = null;
            HashMap<String,BigDecimal> hashMap = new HashMap<>();
            if (wmStockOutList != null && wmStockOutList.size() > 0){
                for (int i = 0; i < wmStockOutList.size(); i++) {
                    WmStockWillOut item = wmStockOutList.get(i);
                    if (i == 0){
                        needIds = item.getLinkId();
                    }else {
                        needIds +=","+item.getLinkId();
                    }
                    hashMap.put(item.getLinkId(),item.getQuantity());
                }
            }else {
                return apiLog.ok(new ArrayList<>());
            }

            Map map = req.getParameterMap();

            LGLeftJoinQueryWrapper lgLeftJoinQueryWrapper = new LGLeftJoinQueryWrapper<>(new ProItemNeed(),map);
            lgLeftJoinQueryWrapper.setDefaultDateFormat("yyyy-MM-dd HH:mm:ss");
            lgLeftJoinQueryWrapper.whereOtherSql(" and record_id in ("+needIds+")");
            lgLeftJoinQueryWrapper.orderBy("need_date");
            IPage<JSONObject> pageList = wmStockOutService.lgPageMapList(lgLeftJoinQueryWrapper);
            for (int i = 0;i < pageList.getRecords().size();i++){
                String recordId = pageList.getRecords().get(i).getString("recordId");
                BigDecimal bigDecimal = hashMap.get(recordId);
                if (bigDecimal != null){
                    if (bigDecimal.intValue() == bigDecimal.floatValue()){
                        pageList.getRecords().get(i).put("willOut",bigDecimal.intValue());
                    }else {
                        pageList.getRecords().get(i).put("willOut",String.format("%.2f",bigDecimal.floatValue()));
                    }
                }
            }
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 客户需求，获取库存信息和在产信息
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:materialStock')")
    @Log(title = "客户需求，获取库存信息和生产排产预出库信息", businessType = BusinessType.EXPORT)
    @GetMapping("/materialStock")
    public Result<IPage<ProItemNeed>> materialStock(ProItemNeed proItemNeed,
                                           @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                           HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询客戶产品需求列表",req,null);
        try {
            if (proItemNeed.getItemId() == null){
                return apiLog.fail("产品不能为空");
            }
            proItemNeed = proItemNeedService.getById(proItemNeed.getRecordId());
            Map<String,List> map = new HashMap<>();
            //获取产品
//            QueryWrapper<MdItem> proItemNeedQueryWrapper = new QueryWrapper<>();
//            proItemNeedQueryWrapper.eq("item_code",proItemNeed.getItemCode());
//            proItemNeedQueryWrapper.last("limit 1");
            map = getMdStock(proItemNeed);
            return apiLog.ok(map);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 跟换客户需求，获取库存信息和在产信息
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:materialStock')")
    @GetMapping("/materialStock2")
    public Result<IPage<ProItemNeed>> materialStock2(MdItem mdItem,
                                                    @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                    @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                    HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询客戶产品需求列表",req,null);
        try {
            if (mdItem.getItemId() == null && mdItem.getProcessProductName() == null){
                return apiLog.fail("MES分类不能为空");
            }
            //获取产品
            MdItem needItem = mdItemService.getById(mdItem.getItemId());

            String stringNames = null;
            //获取统计分类BOM
            if (mdItem.getItemId() != null){
                MdProductStatisticsBom statisticsBom = new MdProductStatisticsBom();
                statisticsBom.setItemId(Long.valueOf(mdItem.getItemId()));
                QueryWrapper<MdProductStatisticsBom> mdProductBomQueryWrapper = new QueryWrapper<>(statisticsBom);
                List<MdProductStatisticsBom> statisticsBomList = statisticsBomService.list(mdProductBomQueryWrapper);

                stringNames = "'"+needItem.getProcessProductName()+"'";
                if (statisticsBomList != null){
                    for (int i = 0;i < statisticsBomList.size();i++){
                        stringNames += ","+"'"+ statisticsBomList.get(i).getStatisticsName()+"'";
                    }
                }
            }

            List<Map> wmMaterialStockList = wmStockWillOutService.materStockWithWillOut2(stringNames,mdItem.getProcessProductName());

            Map<String,List> map = new HashMap<>();
            map.put("materialStockList",wmMaterialStockList);

            return apiLog.ok(map);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 导出客戶产品需求列表
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:export')")
    @Log(title = "客戶产品需求", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProItemNeed proItemNeed,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出客戶产品需求列表",req,proItemNeed);
        try {
            List<ProItemNeed> list = proItemNeedService.queryList(proItemNeed);
            ExcelUtil<ProItemNeed> util = new ExcelUtil<ProItemNeed>(ProItemNeed.class);
            util.exportExcel(response, list, "客戶产品需求数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取客戶产品需求详细信息
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:query')")
    @GetMapping(value = "/{recordId}")
    public Result<ProItemNeed> getInfo(@PathVariable("recordId") Long recordId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取客戶产品需求详细信息",req,null);
        try {
            return apiLog.ok(proItemNeedService.getInfo(recordId));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增客戶产品需求, 不支持备货和发货
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:add')")
    @Log(title = "客戶产品需求", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional
    public Result<String> add(@RequestBody ProItemNeed proItemNeed,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增客戶产品需求",req,proItemNeed);
        try {
            proItemNeed.setShippedType(Long.valueOf(0));
            proItemNeed.setStockCount(BigDecimal.valueOf(0));
            //修改销售单数量
            mesScalesOrderItemService.addCount(proItemNeed.getScalesOrderItemId(), proItemNeed.getNeedCount().doubleValue(),null,null);

            proItemNeedService.insert(proItemNeed);

            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 修改客戶产品需求 - 默认更新需求信息
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:edit')")
    @Log(title = "客戶产品需求 - ", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    @Transactional
    public Result<String> edit(@RequestBody ProItemNeed proItemNeed,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改客戶产品需求",req,proItemNeed);
        try {
            if (proItemNeed.getShippedType() > 0 ){
                return apiLog.fail("请先通知删除备货信息");
            }

            ProItemNeed proItemNeed1 = proItemNeedService.getById(proItemNeed.getRecordId());

            proItemNeed.setShippedType(0L);
            proItemNeedService.update(proItemNeed);

            double aaa =  proItemNeed.getNeedCount().doubleValue() - proItemNeed1.getNeedCount().doubleValue();

            mesScalesOrderItemService.addCount(proItemNeed.getScalesOrderItemId(), aaa,null,null);


            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 修改客戶产品需求 - 删除备货信息
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:deleteStock')")
    @Log(title = "客戶产品需求 - ", businessType = BusinessType.UPDATE)
    @PutMapping("/deleteStock")
    @Transactional
    public Result<String> deleteStock(@PathVariable Long[] recordIds,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改客戶产品需求",req,null);
        try {
            for (int i = 0;i < recordIds.length;i++){
                ProItemNeed proItemNeed = proItemNeedService.getById(recordIds[i]);
                proItemNeedService.deleteStockInfo(String.valueOf(proItemNeed.getRecordId()));

                WmStockWillOut willOut = new WmStockWillOut();
                willOut.setLinkId(String.valueOf(proItemNeed.getRecordId()));
                willOut.setLinkType("pro_item_need");
                wmStockWillOutService.remove( new QueryWrapper<WmStockWillOut>(willOut));
            }
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 修改客戶产品需求 - 确定预出库
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:sureWillOutStock')")
    @Log(title = "客戶产品需求 - ", businessType = BusinessType.UPDATE)
    @PutMapping("/sureWillOutStock")
    public Result<String> sureWillOutStock(@RequestBody Long recordId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改客戶产品需求",req,recordId);
        try {

            ProItemNeed proItemNeed = proItemNeedService.getById(recordId);
            if (proItemNeed == null){
                return apiLog.fail("数据不存在");
            }

            Result result = wmStockWillOutService.isWillOutStatus(Long.valueOf(proItemNeed.getItemId()),String.valueOf(proItemNeed.getRecordId()),null,null,0);
            if (result.getCode() != 0){
                return apiLog.fail(result.getMsg());
            }
            proItemNeed.setShippedType(10L);
            proItemNeedService.update(proItemNeed);

            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 修改客戶产品需求 - 备货状态进入待安排状态
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:deleteWillOutStock')")
    @Log(title = "客戶产品需求 - ", businessType = BusinessType.UPDATE)
    @PutMapping("/deleteWillOutStock")
    @Transactional
    public Result<String> deleteWillOutStock(@RequestBody Long recordId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改客戶产品需求",req,recordId);

        WmIssueLine wmIssueLine = new WmIssueLine();
        wmIssueLine.setItemNeedId(recordId);
        wmIssueLine.setOutType("备货");
        QueryWrapper queryWrapper = new QueryWrapper<>(wmIssueLine);
        List<WmIssueLine> issueLines = issueLineService.list(queryWrapper);

        //修改待发货状态为带安排
        SqlResult result = issueLineService.deleteSQLModelList(issueLines);
        if (result.isSuccess()){
            ProItemNeed proItemNeed = proItemNeedService.getById(recordId);
            proItemNeed.setShippedType(0L);
            proItemNeedService.updateById(proItemNeed);

        }

        return apiLog.sqlResult(result);
    }


    /**
     * 修改客戶产品需求  - 默认备货状态
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:editStock')")
    @Log(title = "客戶产品需求 - 默认备货状态", businessType = BusinessType.UPDATE)
    @PutMapping("/editStock")
    public Result<String> editStock(@RequestBody ProItemNeed proItemNeed,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改客戶产品需求",req,proItemNeed);
        try {
            proItemNeed.setShippedType(20L);
            proItemNeed.setShippedUserId(String.valueOf(SecurityUtils.getUserId()));
            proItemNeed.setShippedUserName(SecurityUtils.getUsername());
            proItemNeedService.update(proItemNeed);

            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 修改客戶产品需求  - 发货
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:editShipped')")
    @Log(title = "客戶产品需求 - 默认发货状态", businessType = BusinessType.UPDATE)
    @PostMapping("/editShipped")
    @Transactional
    public Result<String> editShipped(@RequestBody Long recordId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改客戶产品需求",req,recordId);
        try {
            ProItemNeed proItemNeed = proItemNeedService.getById(recordId);
            if (proItemNeed == null){
                return apiLog.fail("数据不存在");
            }

            WmIssueLine issueLine = new WmIssueLine();
            issueLine.setItemNeedId(proItemNeed.getRecordId());
            issueLine.setOutType("备货");
            QueryWrapper queryWrapper = new QueryWrapper<>(issueLine);
            queryWrapper.select("sum(quantity) as quantity,item_need_id");
            queryWrapper.groupBy("item_need_id");
            issueLine = issueLineService.getOne(queryWrapper);

            if (issueLine.getQuantity().floatValue() < proItemNeed.getNeedCount().floatValue()){
                return apiLog.fail("备货数量不满足发货数量");
            }
            if (issueLine.getQuantity().floatValue() > proItemNeed.getNeedCount().floatValue()){
                return apiLog.fail("备货数量大于发货数量");
            }

            proItemNeed.setShippedType(30L);

            WmStockWillOut willOut = new WmStockWillOut();
            willOut.setLinkId(String.valueOf(proItemNeed.getRecordId()));
            willOut.setLinkType("pro_item_need");


            WmIssueLine issueLine1 = new WmIssueLine();
            issueLine1.setItemNeedId(proItemNeed.getRecordId());
            issueLine1.setOutType("备货");
            UpdateWrapper queryWrapper1 = new UpdateWrapper<>(issueLine1);
            queryWrapper1.set("out_type","发货");
            boolean b = creatDeliveryOrder(proItemNeed,queryWrapper1);
            if(b){
                proItemNeedService.update(proItemNeed);
                wmStockWillOutService.remove( new QueryWrapper<WmStockWillOut>(willOut));
                issueLineService.update(queryWrapper1);
                return apiLog.ok("编辑成功！");
            }else{
                return apiLog.fail("发货失败！");
            }
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 订单发货，推送订单出库单到T+
     * @return
     */
    private boolean creatDeliveryOrder(ProItemNeed proItemNeed,UpdateWrapper updateWrapper) throws ChanjetApiException {
        QueryOrderVo vo = new QueryOrderVo();
        MesScalesOrderItem mesScalesOrderItem = mesScalesOrderItemService.getById(proItemNeed.getScalesOrderItemId());
        if(mesScalesOrderItem == null) return false;
        MesScalesOrder mesScalesOrder = iMesScalesOrderService.getById(mesScalesOrderItem.getScalesOrderId());
        if(mesScalesOrder == null) return false;
        if(!"TPLUS".equals(mesScalesOrder.getDataSource())) return true;
        QueryWrapper<WmIssueLine> wrapper = new QueryWrapper();
        wrapper.eq("item_need_id",proItemNeed.getRecordId()).eq("item_id",new BigDecimal(proItemNeed.getItemId()).longValue());
        WmIssueLine wmIssueLine = issueLineService.getOne(wrapper);
        if(wmIssueLine == null) return false;

        vo.setVourcherId(new BigDecimal((mesScalesOrder.getScalesOrderId())).intValue());
        GetVoucherResponse response = chanjetSpi.getVoucherOrder(vo);
        Map<String, Object> data = response.getData();
        if(data == null) return false;
        ArrayList<LinkedTreeMap> saleOrderDetails = (ArrayList)data.get("SaleOrderDetails");
        Map itemMap = new LinkedMap();
        saleOrderDetails.stream().forEach(map->{
            Map inventoryMap = (LinkedTreeMap)map.get("Inventory");
            String id = new BigDecimal((Double)inventoryMap.get("ID")).longValue() + "";
            if(mesScalesOrderItem.getScalesOrderItemId().equals(id)){
                itemMap.put("item",map);
            }
        });
        if(itemMap.get("item") == null) return false;
        LinkedTreeMap itemDetail = (LinkedTreeMap)itemMap.get("item");
        Date date = new Date();
        JSONObject paramObj = new JSONObject();
        String externalCode = System.currentTimeMillis() + "";
        paramObj.put("ExternalCode",externalCode);
        paramObj.put("Code",externalCode);
        paramObj.put("VoucherDate", DateUtils.dateTime(date));
        paramObj.put("DispatchAddress",data.get("Address"));
        paramObj.put("Contact",data.get("LinkMan"));
        paramObj.put("ContactPhone",data.get("CustomerPhone"));
        if(data.get("Customer") != null){
            JSONObject partnerObj = new JSONObject();
            Map customer = (LinkedTreeMap)data.get("Customer");
            partnerObj.put("Code",customer.get("Code"));
            paramObj.put("Partner",partnerObj);
        }
        if(data.get("SettleCustomer")!=null){
            JSONObject settleCustomerObj = new JSONObject();
            Map settleCustomerMap = (LinkedTreeMap)data.get("SettleCustomer");
            settleCustomerObj.put("Code",settleCustomerMap.get("Code"));
            paramObj.put("SettleCustomer",settleCustomerObj);
        }
        if(data.get("BusinessType")!=null){
            JSONObject businessTypeObj = new JSONObject();
            Map businessTypeMap = (LinkedTreeMap)data.get("BusinessType");
            businessTypeObj.put("Code",businessTypeMap.get("Code"));
            paramObj.put("BusiType",businessTypeObj);
        }
        JSONObject rdStyleObj = new JSONObject();
        rdStyleObj.put("Code","201"); // 销售出库
        paramObj.put("RdStyle",rdStyleObj);
        if(data.get("Project") != null){
            JSONObject projectObj = new JSONObject();
            Map projectMap = (LinkedTreeMap)data.get("Project");
            projectObj.put("Code",projectMap.get("Code"));
            paramObj.put("Project",projectObj);
        }
        JSONObject warehouseObj = new JSONObject();
        warehouseObj.put("Code",wmIssueLine.getWarehouseCode());
        paramObj.put("Warehouse",warehouseObj);
        if(data.get("Clerk") != null){
            JSONObject clerkObj = new JSONObject();
            Map clerkMap = (LinkedTreeMap)data.get("Clerk");
            clerkObj.put("Code",clerkMap.get("Code"));
            paramObj.put("Clerk",clerkObj);
        }
        if(data.get("LogisticsNetwork") !=null){
            JSONObject logisticsNetwork = new JSONObject();
            Map LogisticsNetworkMap = (LinkedTreeMap)data.get("LogisticsNetwork");
            logisticsNetwork.put("Code",LogisticsNetworkMap.get("Code"));
            paramObj.put("LogisticsNetwork",logisticsNetwork);
        }
        if(data.get("LogisticsStatus") != null){
            JSONObject obj = new JSONObject();
            Map map = (LinkedTreeMap)data.get("LogisticsStatus");
            obj.put("Code",map.get("Code"));
            paramObj.put("LogisticsStatus",obj);
        }
        if(data.get("Department") != null){
            JSONObject obj = new JSONObject();
            Map map = (LinkedTreeMap)data.get("Department");
            obj.put("Code",map.get("Code"));
            paramObj.put("Department",obj);
        }
        JSONObject rdRecordDetails = new JSONObject();  // 明细信息
        rdRecordDetails.put("BaseQuantity",proItemNeed.getNeedCount());
        rdRecordDetails.put("origTaxSalePrice",itemDetail.get("OrigTaxPrice"));
        if(itemDetail.get("DetailMemo") != null){
            rdRecordDetails.put("DetailMemo",itemDetail.get("DetailMemo"));
        }
        rdRecordDetails.put("Batch",wmIssueLine.getBatchCode());
        rdRecordDetails.put("idsourcevouchertype",43);
        rdRecordDetails.put("sourceVoucherCode",mesScalesOrder.getScalesOrderCode());
        rdRecordDetails.put("sourceVoucherDetailId",new BigDecimal((Double)itemDetail.get("ID")).longValue());
        JSONObject inventoryObj = new JSONObject();
        inventoryObj.put("Code",mesScalesOrderItem.getScalesOrderItemCode());
        rdRecordDetails.put("Inventory",inventoryObj);
        JSONObject unitObj = new JSONObject();
        unitObj.put("Name",mesScalesOrderItem.getUnitOfMeasure());
        rdRecordDetails.put("Unit",unitObj);
        ArrayList list = new ArrayList<>();
        list.add(rdRecordDetails);
        paramObj.put("RDRecordDetails",list);
        DeliveryOrderContent content = new DeliveryOrderContent();
        content.setDto(paramObj);
        GetVoucherResponse getVoucherResponse = chanjetSpi.saleDispatchCreate(content);
        if(getVoucherResponse.getCode() == 0){
            Map<String, Object> result = getVoucherResponse.getData();
            String code = (String)result.get("Code");
            updateWrapper.set("out_order_code",code);
            return true;
        }else{
            String message = getVoucherResponse.getMessage();
            return false;
        }
    }



    /**
     * 删除客戶产品需求
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:remove')")
    @Log(title = "客戶产品需求", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recordIds}")
    @Transactional
    public Result<String> remove(@PathVariable Long[] recordIds,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除客戶产品需求",req,null);
        try {
            for (int i = 0; i < recordIds.length; i++) {

                ProItemNeed proItemNeed1 = proItemNeedService.getById(recordIds[i]);
                mesScalesOrderItemService.addCount(proItemNeed1.getScalesOrderItemId(), -proItemNeed1.getNeedCount().doubleValue(),null,null);


                WmStockWillOut willOut = new WmStockWillOut();
                willOut.setLinkId(String.valueOf(proItemNeed1.getRecordId()));
                willOut.setLinkType("pro_item_need");
                wmStockWillOutService.remove( new QueryWrapper<WmStockWillOut>(willOut));

            }
            proItemNeedService.delete(recordIds);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 按天获取库存统计
     */
    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:getDayStock')")
    @Log(title = "客戶产品需求", businessType = BusinessType.DELETE)
    @GetMapping("/getDayStock")
    public Result<String> getDayStock(HttpServletRequest req) {
        QueryWrapper proItemNeedQueryWrapper = new QueryWrapper<ProItemNeed>();
        proItemNeedQueryWrapper.select("item_id, item_name, viscosity, tag, packing_type, DATE_FORMAT( need_date, '%Y-%m-%d' ) as requestDate, SUM( need_count ) AS allCount");
        proItemNeedQueryWrapper.le("need_date","NOW()");
        proItemNeedQueryWrapper.groupBy("item_id,DATE_FORMAT(need_date, '%Y-%m-%d')");
        List<ProItemNeed> proItemNeedList = proItemNeedService.list(proItemNeedQueryWrapper);


        ArrayList itemSubNameList = new ArrayList<>();
        ArrayList itemSubViscosityList = new ArrayList<>();
        if (proItemNeedList != null && proItemNeedList.size() > 0){
            for (ProItemNeed item: proItemNeedList ) {
                String itemName = item.getItemName();
                String viscosity = item.getViscosity();
//                itemNameList.add(itemName);
//                itemViscosityList.add(viscosity);

//                itemSubNameList.add()
            }
        }
        return Result.OK();
    }

    private Map getMdStock(ProItemNeed proItemNeed){
        MdItem needItem = mdItemService.getById(Long.valueOf(proItemNeed.getItemId()));

        //获取统计分类BOM
        List<MdProductStatisticsBom> statisticsBomList = statisticsBomService.findBomNotMaterial(Long.valueOf(proItemNeed.getItemId()));

        String stringNames = "'"+needItem.getProcessProductName()+"'";
        if (statisticsBomList != null){
            for (int i = 0;i < statisticsBomList.size();i++){
                stringNames += ","+"'"+ statisticsBomList.get(i).getStatisticsName()+"'";
            }
        }

        List<Map> wmMaterialStockList = wmStockWillOutService.materStockWithWillOut(stringNames, String.valueOf(proItemNeed.getRecordId()),Long.valueOf(proItemNeed.getItemId()));
        List<Map> proWorkorderList =  wmStockWillOutService.prokorderWithWillOut(stringNames, String.valueOf(proItemNeed.getRecordId()));
        List<ProItemNeed> proItemNeedList = wmStockWillOutService.relationProItemNeed(stringNames,String.valueOf(proItemNeed.getRecordId()));

        List<Map> findmaterStockAllWillOut = wmStockWillOutService.materStockAllWillOut(stringNames,String.valueOf(proItemNeed.getRecordId()));
        List<Map> findprokorderAllWillOut = wmStockWillOutService.prokorderAllWillOut(stringNames,String.valueOf(proItemNeed.getRecordId()));

        Map<String,List> map = new HashMap<>();
        map.put("materialStockList",wmMaterialStockList);
        map.put("proWorkorderList",proWorkorderList);
        map.put("proItemNeedList",proItemNeedList);

        Map<String,Float> floatMap = new HashMap<>();
        String[] nameList = stringNames.split(",");
        List<Map> materStockAllWillOut = new ArrayList<>();
        List<Map> prokorderAllWillOut = new ArrayList<>();

        for (int i = 0;i < nameList.length;i++){
            String name = nameList[i].replace("'","");
            Map ma1 = null;
            for (int j = 0;j < findmaterStockAllWillOut.size();j++){
                if (findmaterStockAllWillOut.get(j).get("process_product_name").toString().equals(name)){
                    ma1 = findmaterStockAllWillOut.get(j);
                    continue;
                }
            }
            if (ma1 == null){
                ma1 = new HashMap<>();
                ma1.put("process_product_name",name);
                ma1.put("allwillout",Float.valueOf(0));
            }
            materStockAllWillOut.add(ma1);

            Map ma2 = null;
            for (int j = 0;j < findprokorderAllWillOut.size();j++){
                if (findprokorderAllWillOut.get(j).get("process_product_name").toString().equals(name)){
                    ma2 = findprokorderAllWillOut.get(j);
                    continue;
                }
            }
            if (ma2 == null){
                ma2 = new HashMap<>();
                ma2.put("process_product_name",name);
                ma2.put("allwillout",Float.valueOf(0));
            }
            prokorderAllWillOut.add(ma2);
        }

        if (materStockAllWillOut != null){
            for (int i = 0; i < materStockAllWillOut.size(); i++) {
                Map it = materStockAllWillOut.get(i);
                String name = it.get("process_product_name").toString();
                float ss = Float.valueOf(it.get("allwillout").toString()).floatValue();
                Float f = floatMap.get(name);
                if (f == null){
                    floatMap.put(name,Float.valueOf(ss));
                }else {
                    floatMap.put(name,Float.valueOf(ss+f.floatValue()));
                }
            }
        }

        if (prokorderAllWillOut != null ) {
            for (int i = 0; i < prokorderAllWillOut.size(); i++) {
                Map it = prokorderAllWillOut.get(i);
                String name = it.get("process_product_name").toString();
                float ss = Float.valueOf(it.get("allwillout").toString()).floatValue();
                Float f = floatMap.get(name);
                if (f == null) {
                    floatMap.put(name, Float.valueOf(ss));
                } else {
                    floatMap.put(name, Float.valueOf(ss + f.floatValue()));
                }
            }
        }
        for (int i = 0; i < materStockAllWillOut.size(); i++) {
            Map map1 = materStockAllWillOut.get(i);
            String name = map1.get("process_product_name").toString();
            map1.put("allwillout",floatMap.get(name));
        }
        map.put("materStockAllWillOut",materStockAllWillOut);


        //统计半成品的需求量
        //获取预出的的成品数量
        Float f = floatMap.get(needItem.getProcessProductName());
        float bl = proItemNeed.getNeedCount().floatValue();
        Map<String,Float> aaa = new HashMap<>();
        if (f != null){
            bl = proItemNeed.getNeedCount().floatValue() - f.intValue();
        }
        aaa.put(needItem.getProcessProductName(),bl);

        for (int i = 0;i < statisticsBomList.size();i++){
            MdProductStatisticsBom bom = statisticsBomList.get(i);
            float 剩余量 = bom.getQuantity().floatValue()*bl;
            Float f2 = floatMap.get(bom.getStatisticsName());
            if (f2 != null){
                aaa.put(bom.getStatisticsName(),Float.valueOf(剩余量-f2.floatValue()));
            }else {
                aaa.put(bom.getStatisticsName(),Float.valueOf(剩余量));
            }
        }
        List needAllWillOut = new ArrayList<>();
        for (int i = 0; i < materStockAllWillOut.size(); i++) {
            Map map2 = new HashMap<>();
            Map map1 = materStockAllWillOut.get(i);
            String name = map1.get("process_product_name").toString();
            Float flo = aaa.get(name);
            if (flo != null){
                map2.put("allwillout",String.format("%.2f",flo.floatValue()));
            }
            map2.put("process_product_name",name);
            needAllWillOut.add(map2);
        }
        map.put("needAllWillOut",needAllWillOut);
        return map;
    }

}
